import Vue from 'vue'
import store from '../store'
import setting from '../settings'
const superAdminRole = setting.superAdminRole

Vue.prototype.$hasPermission = (permission) => {
  const userPermission = store.state.auth.permissions
  if (store.state.auth.roles.indexOf(superAdminRole) > -1) return true
  if (!userPermission) return false

  if (permission.indexOf('&&') > -1) {
    return !permission.split('&&').some(item => userPermission.indexOf(item) === -1)
  } else if (permission.indexOf('||') > -1) {
    return permission.split('||').some(item => userPermission.indexOf(item) > -1)
  } else {
    return userPermission.indexOf(permission) > -1
  }
}

Vue.directive('hasPermission', {
  bind: (el, binding) => {
    if (!Vue.prototype.$hasPermission(binding.value)) {
      Vue.nextTick(() => {
        el.parentNode.removeChild(el)
      })
    }
  }
})

Vue.directive('noPermission', {
  bind: (el, binding) => {
    if (Vue.prototype.$hasPermission(binding.value)) {
      Vue.nextTick(() => {
        el.parentNode.removeChild(el)
      })
    }
  }
})
